package com.situ.orderingsystem.global;

import com.situ.orderingsystem.model.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

//@WebFilter("/*")
public class LoginFilter implements Filter {
    private  static final List<String> whiteList = List.of("/user/login","/user/logout","/user/captcha");
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        User user = (User)session.getAttribute(Global.USER_LOGIN_KEY);

        String uri =req.getRequestURI();
//        System.out.println(url);

        String ctx = req.getContextPath();
        String action = uri.replace(ctx,"");


        boolean match = false;
        if (uri.endsWith(".js") || uri.endsWith(".css") || uri.endsWith(".jpg")) {
            match = true;
        }else{
            for(String url : whiteList){
                if(action.startsWith(url)){
                    match =true;
                    break;
                }
            }
        }

        if(match){
           chain.doFilter(req,resp);
        }else{
            if(user == null){
                resp.sendRedirect(req.getContextPath()+"/user/login");
            }else{
                chain.doFilter(req,resp);
            }
        }



    }
}
